<script setup lang="ts">
import { ref, onMounted, watch } from "vue";
import { useRoute } from "vue-router";
import { tabsList } from "./helps";
import {
  getCeyeConfigs,
  getCeyeStatistics,
  clearCeyeRecords,
  testCeyeConnection,
} from "./servers";
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
import DNSRecord from "./components/DNSRecord.vue";
import HTTPRecord from "./components/HTTPRecord.vue";
import AllRecord from "./components/AllRecord.vue";

const route = useRoute();

// 获取URL参数中的task
const taskParam = ref((route.query.task as string) || "");

// Ceye 配置相关
const configList = ref<any[]>([]);
const selectedConfig = ref("");
const ceyeDomain = ref("");

// 统计数据
const statistics = ref({
  dns_count: 0,
  http_count: 0,
  total_count: 0,
  used_today: 0,
  daily_quota: 1000,
  quota_percentage: 0,
  ceye_domain: "",
  last_query_time: "",
  query_time: "",
});

const loading = ref(false);
const loadingStatistics = ref(false);

// 加载配置列表
const loadConfigs = async () => {
  try {
    const { data } = await getCeyeConfigs();

    configList.value = data.configs || [];
    selectedConfig.value = data.default_config || "default";

    // 设置当前配置的域名
    const currentConfig = configList.value.find(
      (c) => c.config_name === selectedConfig.value
    );
    if (currentConfig) {
      ceyeDomain.value = currentConfig.ceye_domain || "";
    }
  } catch (error: any) {
    console.error("获取配置列表失败:", error);
    ElMessage.error("获取配置列表失败");
  }
};

// 加载统计数据
const loadStatistics = async () => {
  if (!selectedConfig.value) return;

  loadingStatistics.value = true;
  try {
    const data = await getCeyeStatistics({
      config_name: selectedConfig.value,
    });
    statistics.value = {
      dns_count: data.data.dns_count || 0,
      http_count: data.data.http_count || 0,
      total_count: data.data.total_count || 0,
      used_today: data.data.used_today || 0,
      daily_quota: data.data.daily_quota || 1000,
      quota_percentage: data.data.quota_percentage || 0,
      ceye_domain: data.data.ceye_domain || "",
      last_query_time: data.data.last_query_time || "",
      query_time: data.data.query_time || "",
    };
    // 更新域名显示
    if (data.data.ceye_domain) {
      ceyeDomain.value = data.data.ceye_domain;
    }
  } catch (error) {
    console.error("获取统计数据失败:", error);
    ElMessage.error("获取统计数据失败");
  } finally {
    loadingStatistics.value = false;
  }
};

// 配置变化处理
const handleConfigChange = () => {
  const currentConfig = configList.value.find(
    (c) => c.config_name === selectedConfig.value
  );
  if (currentConfig) {
    ceyeDomain.value = currentConfig.ceye_domain || "";
  }
  loadStatistics();
};

// 刷新统计数据
const handleRefresh = () => {
  loadStatistics();
  ElMessage.success("刷新成功");
};

// 清空记录
const handleClearRecords = async () => {
  try {
    await ElMessageBox.confirm(
      "确定要清空所有记录吗？此操作不可恢复！",
      "警告",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    loading.value = true;
    const response = await clearCeyeRecords({
      config_name: selectedConfig.value,
      confirm: true,
    });

    const data = response.data || response;
    if (data.code === 2000) {
      ElMessage.success(data.message || "清空成功");
      // 刷新统计数据
      loadStatistics();
      // 刷新记录列表（DNS、HTTP、全部记录）
      // 通过 watch 监听 selectedConfig 变化，子组件会自动刷新
    } else {
      ElMessage.error(data.message || "清空失败");
    }
  } catch (error: any) {
    if (error !== "cancel") {
      console.error("清空记录失败:", error);
      ElMessage.error(error.message || "清空记录失败");
    }
  } finally {
    loading.value = false;
  }
};

// 测试连接
const handleTestConnection = async () => {
  loading.value = true;
  try {
    const data = await testCeyeConnection({
      config_name: selectedConfig.value,
    });

    const testData = data.data || {};
    const success = testData.success || testData.connected;

    if (success) {
      ElNotification({
        title: "连接测试成功",
        message: `域名: ${testData.domain || ceyeDomain.value}\n响应时间: ${
          testData.response_time ? testData.response_time + "ms" : "未知"
        }\n记录数: ${testData.record_count || 0}`,
        type: "success",
        duration: 4000,
      });
    } else {
      ElMessage.warning(data.message || "连接测试失败");
    }
  } catch (error: any) {
    console.error("连接测试失败:", error);
    ElMessage.error(error.message || "连接测试失败");
  } finally {
    loading.value = false;
  }
};

// 监听配置变化
watch(selectedConfig, () => {
  handleConfigChange();
});

// 初始化
onMounted(() => {
  loadConfigs();
  loadStatistics();
});
</script>

<template>
  <div>
    <el-card style="margin-bottom: 16px">
      <template #header>
        <div class="ceye-header">
          <div class="config-area">
            <span class="label">配置选择:</span>
            <el-select
              v-model="selectedConfig"
              placeholder="请选择配置"
              style="width: 200px; margin-right: 20px"
              @change="handleConfigChange"
            >
              <el-option
                v-for="config in configList"
                :key="config.config_name"
                :label="config.config_name"
                :value="config.config_name"
              />
            </el-select>
            <span class="label">域名:</span>
            <span class="domain-value">{{ ceyeDomain || "-" }}</span>
          </div>
          <div class="action-buttons">
            <el-button type="primary" @click="handleRefresh"> 刷新 </el-button>
            <el-button
              type="danger"
              @click="handleClearRecords"
              :loading="loading"
            >
              清空记录
            </el-button>
            <el-button
              type="success"
              @click="handleTestConnection"
              :loading="loading"
            >
              测试连接
            </el-button>
          </div>
        </div>
      </template>

      <div class="statistics-card">
        <div class="stat-item">
          <span class="stat-label">DNS 记录:</span>
          <span class="stat-value">{{ statistics.dns_count }} 条</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">HTTP 记录:</span>
          <span class="stat-value">{{ statistics.http_count }} 条</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">总计:</span>
          <span class="stat-value">{{ statistics.total_count }} 条</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">配额:</span>
          <span class="stat-value">
            {{ statistics.used_today }}/{{ statistics.daily_quota }} ({{
              statistics.quota_percentage.toFixed(1)
            }}%)
          </span>
        </div>
        <div class="stat-item">
          <span class="stat-label">最后查询:</span>
          <span class="stat-value">
            {{ statistics.last_query_time || statistics.query_time || "-" }}
          </span>
        </div>
      </div>
    </el-card>
    <el-tabs type="border-card">
      <el-tab-pane
        v-for="item in tabsList"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      >
        <div
          v-if="taskParam"
          style="display: flex; justify-content: space-between"
        >
          <div class="task-name">任务名称：{{ taskParam }}</div>
        </div>
        <DNSRecord
          v-if="item.key === 'dns_record'"
          :config-name="selectedConfig"
        />
        <HTTPRecord
          v-if="item.key === 'http_record'"
          :config-name="selectedConfig"
        />
        <AllRecord
          v-if="item.key === 'all_record'"
          :config-name="selectedConfig"
          :task="taskParam"
        />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<style lang="scss" scoped>
.search-form-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.search-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

.el-btn-zese {
  background: #722ed1;
  color: white;
  border-color: #722ed1;
}

.el-btn-zese.is-disabled,
.el-btn-zese.is-disabled:focus,
.el-btn-zese.is-disabled:hover {
  background: #722ed1;
  color: white;
  border-color: #722ed1;
}
.task-name {
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 10px;
  border: 1px solid #e0e0e0;
  padding: 10px;
  border-radius: 5px;
}

.ceye-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;

  .config-area {
    display: flex;
    align-items: center;
    gap: 8px;

    .label {
      font-weight: 500;
      color: #606266;
    }

    .domain-value {
      color: #409eff;
      font-weight: 500;
    }
  }

  .action-buttons {
    display: flex;
    gap: 12px;
    flex-wrap: wrap;
  }
}

.statistics-card {
  display: flex;
  flex-wrap: wrap;
  gap: 24px;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 8px;
  border: 1px solid #e4e7ed;

  .stat-item {
    display: flex;
    flex-direction: column;
    gap: 8px;
    min-width: 150px;

    .stat-label {
      font-size: 14px;
      color: #909399;
      font-weight: 500;
    }

    .stat-value {
      font-size: 18px;
      color: #303133;
      font-weight: bold;
    }
  }
}

@media (max-width: 768px) {
  .ceye-header {
    flex-direction: column;
    align-items: flex-start;

    .action-buttons {
      width: 100%;
      justify-content: flex-start;
    }
  }

  .statistics-card {
    flex-direction: column;
    gap: 16px;
  }
}
</style>
